package cn.shop.cloud.mq;

import cn.shop.cloud.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @program: work
 * @ClassName OrderMQListener
 * @description: 订单监听类
 * @author: 李尧坤
 * @create: 2025−01-10 13:41
 * @Version 1.0
 **/

@Component
public class MqOrderMQListener {

    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(name = MQConstants.ORDER_RESULT_NOTIFY_QUEUE),
                    exchange = @Exchange(name = MQConstants.ORDER_RESULT_EXCHANGE,type = "topic"),
                    key = MQConstants.ORDER_RESULT_NOTIFY_KEY)
    )
    public void handlerOrderResultQueue(@Payload Map<String,Object> param,
                                        @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag,
                                        Channel channel){

        //方法体
        String uuid = (String) param.get("uuid");

        int flag=3;
        WebSocketServer ws = null;
        while(flag>0){
            ws = WebSocketServer.clients.get(uuid);
            if(ws!=null){
                try {
                    ws.getSession().getBasicRemote().sendText(JSON.toJSONString(param));
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            flag--;
        }

        try {
            TimeUnit.MILLISECONDS.sleep(100);// 0.1
        } catch (InterruptedException e) {
            e.printStackTrace();
            //运维跑步过来
        }finally {
            try {
                channel.basicAck(deliveryTag,false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
